package com.md.application.assembler;

import com.md.base.exception.ServerException;
import com.md.domain.model.bo.QueryRoleBO;
import com.md.domain.model.po.RolePO;
import com.md.request.QueryRolePageRequest;
import com.md.request.RoleRequest;
import com.md.response.RoleModuleResponse;
import com.md.response.RoleResponse;
import com.md.util.ClassUtils;
import com.md.util.ObjectUtil;
import com.md.util.PinYinUtil;
import com.md.value.RoleOrderEnum;
import com.md.value.RoleStatusEnum;
import com.md.value.enums.ErrorEnum;
import lombok.experimental.UtilityClass;

import java.util.List;
import java.util.Optional;

/**
 * @author 刘骄阳
 * 2024-12-15 1:49
 */
@UtilityClass
public class RoleAssembler {

  public static RolePO buildCreateRolePO(final RoleRequest request) {
    return ClassUtils.source2Target(request, RolePO.class, rolePO -> {
      rolePO.setFirstLabel(PinYinUtil.getPinYinHeadChar(request.getName()));
      rolePO.setStatus(RoleStatusEnum.NORMAL.getCode());
    });
  }

  public static RoleResponse buildRole2Response(final RolePO rolePO, final List<RoleModuleResponse> rolePermission) {
    return ClassUtils.source2Target(rolePO, RoleResponse.class, roleResponse -> {
      roleResponse.setStatus(RoleStatusEnum.of(rolePO.getStatus()));
      roleResponse.setRolePermission(rolePermission);
    });
  }

  public static void checkQueryAppInfoList(final Long moduleId) {
    if (ObjectUtil.isEmpty(moduleId)) {
      throw ServerException.build(ErrorEnum.IS_EMPTY, "模块id");
    }
  }

  public static void checkQueryApiList(final Long appInfoId) {
    if (ObjectUtil.isEmpty(appInfoId)) {
      throw ServerException.build(ErrorEnum.IS_EMPTY, "应用id");
    }
  }

  public static void checkUpdateRole(final Long id, final String name) {
    if (ObjectUtil.isEmpty(id)) {
      throw ServerException.build(ErrorEnum.IS_EMPTY, "id");
    }
    if (ObjectUtil.isEmpty(name)) {
      throw ServerException.build(ErrorEnum.IS_EMPTY, "角色名");
    }
  }

  public static void checkCreateRole(final String name) {
    if (ObjectUtil.isEmpty(name)) {
      throw ServerException.build(ErrorEnum.IS_EMPTY, "角色名");
    }
  }

  public static QueryRoleBO buildQueryRoleBO(final QueryRolePageRequest request) {
    return ClassUtils.source2Target(request, QueryRoleBO.class, queryBO -> {
      Optional.ofNullable(request.getOrder()).map(RoleOrderEnum::getColumn).ifPresent(queryBO::setOrderColum);
      Optional.ofNullable(request.getStatus()).map(RoleStatusEnum::getCode).ifPresent(queryBO::setStatus);
      queryBO.setPageNum(request.getPageNum());
      queryBO.setPageSize(request.getPageSize());
    });
  }
}
